<?php
namespace app\index\controller;

use GatewayWorker\Lib\Db;
use think\facade\Request;
use think\facade\Config;
use app\common\traits\Provide;

use \GatewayWorker\Lib\Gateway; //引入GatewayWorker服务框架
//Gateway注册地址
Gateway::$registerAddress = '127.0.0.1:1236';

class Index extends Base
{
    use Provide;
    public function index(Request $request)
    {
        $room_id = (int)input('room_id', 10001);
        $room_info = $this->getRoomInfo($room_id);
        if(!empty($room_info))
        {
            $user_info = session('user_info');
            if(!$user_info)
            {
                $user_info['user_id']   = $this->getUserID();
                $user_info['user_name'] = $this->getTouristName();
                $user_info['user_role'] = "1";         //游客
                $user_info['speak_state'] = 1;  //发言状态 1正常 0禁言
                $user_info['avatar']    = $this->getAvatar($user_info['user_role']);
                $user_info['role_icon'] = $this->getRoleIcon($user_info['user_role']);
                $user_info['room_id']   = $room_id;
                $user_info['token']     = $this->getToken($user_info);
                session('user_info', $user_info);
            }
            $teacher = $this->getTeacherList(1);
            $article_cate = $this->getArticleCate();

            $room_data = array_merge($room_info, $user_info);
            $this->assign('teacher', $teacher);
            $this->assign('article_cate', $article_cate);
            $this->assign('room_data', $room_data);
            return $this->fetch('pc_index');
        }else{
            $this->assign('msg','输入的房间号不存在!');
            return $this->fetch('public/error');
        }
    }

    /**
     * 审核消息
     */
    public function auditMessage()
    {
        $user_info = session('user_info');
        $room_info = $this->getRoomInfo($user_info['room_id']);
        $power_role = explode(',', $room_info['power_role']);
        $msg_cache_index = input('msg_cache_index');
        $from_user_id = input('from_user_id');
        $msg_id = input('msg_id');
        if(in_array($user_info['user_role'], $power_role))
        {
            $room_msg = 'room_msg_'.$user_info['room_id'];
            $msg_info = $this->redis()->lindex($room_msg, $msg_cache_index-1);
            if($msg_info)
            {
                $msg_info = json_decode($msg_info, true);
                $msg_info['is_examine'] = 1;
                $this->redis()->lSet($room_msg, $msg_cache_index-1, json_encode($msg_info));
                //普通房间
                $general_channel = $user_info['room_id'].'_general';
                $user_client_id  = Gateway::getClientIdByUid($from_user_id);
                //如果用户还在线
                if($user_client_id)
                {
                    Gateway::sendToGroup($general_channel, json_encode($msg_info), $user_client_id[0]);
                }else{
                    Gateway::sendToGroup($general_channel, json_encode($msg_info));
                }
                return responseJson(200,'success');
            }else{
                return responseJson(400,'为获取到消息信息');
            }
        }else{
            return responseJson(400,'您无权审核消息');
        }
    }

    /**
     * 管理员撤回消息
     */
    public function powerRecallMessage()
    {
        $user_info = session('user_info');
        $msg_id    = input('msg_id');
        $msg_cache_index = input('msg_cache_index');
        $room_info = $this->getRoomInfo($user_info['room_id']);
        //普通房间
        $general_channel = $user_info['room_id'].'_general';
        //权利房间
        $power_channel   = $user_info['room_id'].'_power';
        $room_msg        = 'room_msg_'.$user_info['room_id'];
        $power_role = explode(',', $room_info['power_role']);
        if(in_array($user_info['user_role'], $power_role))
        {
            $msg['msg_type']   = 'recall_msg';
            $msg['msg_id']     = $msg_id;
            $msg['from_token'] = $user_info['token'];
            Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));
            $msg_info = $this->redis()->lindex($room_msg, $msg_cache_index-1);
            if($msg_info)
            {
                $msg_info = json_decode($msg_info, true);
                $msg_info['msg_state'] = 0;
                $this->redis()->lSet($room_msg, $msg_cache_index-1, json_encode($msg_info));
            }
            return responseJson(200,'success');
        }else{
            return responseJson(400,'您无权操作');
        }
    }

    /**
     * 普通用户撤回消息撤回消息
     */
    public function recallMessage()
    {
        $user_info = session('user_info');
        $from_user_id = input('from_user_id');
        $from_token   = input('from_token');
        $msg_id       = input('msg_id');
        $msg_cache_index = input('msg_cache_index');
        if($from_user_id == $user_info['user_id'])
        {
            //普通房间
            $general_channel = $user_info['room_id'].'_general';
            //权利房间
            $power_channel   = $user_info['room_id'].'_power';

            $room_msg        = 'room_msg_'.$user_info['room_id'];

            $msg['msg_type']   = 'recall_msg';
            $msg['msg_id']     = $msg_id;
            $msg['from_token'] = $from_token;
            Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));

            $msg_info = $this->redis()->lindex($room_msg, $msg_cache_index-1);
            if($msg_info)
            {
                $msg_info = json_decode($msg_info, true);
                $msg_info['msg_state'] = 0;
                $this->redis()->lSet($room_msg, $msg_cache_index-1, json_encode($msg_info));
            }
            return responseJson(200,'success');
        }else{
            return responseJson(400,'仅能撤回自己发送的消息');
        }
    }

    /**
     * 禁言
     */
    public function prohibitSpeak()
    {
        $user_info = session('user_info');
        $from_token   = input('from_token');
        $room_info = $this->getRoomInfo($user_info['room_id']);
        $power_role = explode(',', $room_info['power_role']);
        if(in_array($user_info['user_role'], $power_role))
        {
            $from_user_info = $this->getUserInfoByToken($from_token);
            $from_user_info['speak_state'] = 0;
            $this->redis()->set($from_token, json_encode($from_user_info));
            if($from_user_info['user_role'] !=0)
            {
                $this->editUserState($from_user_info['user_id'], 0);
            }
            return responseJson(200,'success');
        }else
        {
            return responseJson(400,'您无权操作');
        }
    }

    /**
     * 解禁发言
     */
    public function releaseSpeak()
    {
        $user_info = session('user_info');
        $from_token   = input('from_token');
        $room_info = $this->getRoomInfo($user_info['room_id']);
        $power_role = explode(',', $room_info['power_role']);
        if(in_array($user_info['user_role'], $power_role))
        {
            $from_user_info = $this->getUserInfoByToken($from_token);
            $from_user_info['speak_state'] = 1;
            $this->redis()->set($from_token, json_encode($from_user_info));
            if($from_user_info['user_role'] !=0)
            {
                $this->editUserState($from_user_info['user_id'], 1);
            }
            return responseJson(200,'success');
        }else
        {
            return responseJson(400,'您无权操作');
        }
    }

    /**
     * 踢出客户
     */
    public function outClient()
    {
        $user_info = session('user_info');
        $from_token   = input('from_token');
        $room_info = $this->getRoomInfo($user_info['room_id']);
        $power_role = explode(',', $room_info['power_role']);
        if(in_array($user_info['user_role'], $power_role))
        {
            $from_user_info = $this->getUserInfoByToken($from_token);
            $user_client_id  = Gateway::getClientIdByUid($from_user_info['user_id']);
            //如果用户还在线
            if($user_client_id)
            {
                Gateway::closeClient($user_client_id[0]);
                return responseJson(200,'success');
            }else{
                return responseJson(400,'此用户已经下线');
            }
        }else
        {
            return responseJson(400,'您无权操作');
        }
    }

    /*
     * 更改直播信息
     */
    public function changeLive()
    {
        $user_info = session('user_info');
        $from_token   = input('from_token');
        $room_info = $this->getRoomInfo($user_info['room_id']);
        $power_role = explode(',', $room_info['power_role']);
        if(in_array($user_info['user_role'], $power_role))
        {
            $room_info['teacher_name'] = input('teacher_name');
            $room_info['teacher_avatar'] = input('teacher_avatar');
            $room_name = 'room_info_'.$user_info['room_id'];
            $this->redis()->set($room_name, json_encode($room_info));
            //普通房间
            $general_channel = $user_info['room_id'].'_general';
            //权利房间
            $power_channel   = $user_info['room_id'].'_power';

            $msg['msg_type']   = 'change_live';
            $msg['from_token'] = $from_token;
            $msg['teacher_name']   = input('teacher_name');
            $msg['teacher_avatar'] = input('teacher_avatar');
            Gateway::sendToGroup([$general_channel, $power_channel], json_encode($msg));
            return responseJson(200,'更改成功');
        }else
        {
            return responseJson(400,'您无权操作');
        }
    }

    /**
     * 解锁房间密码
     * @return mixed
     */
    public function roomUnlock()
    {
        $room_id  = input('room_id');
        if(request()->isAjax())
        {
            $pwd = input('room_pwd');
            $room_id    = input('room_id');
            $room_info = $this->getRoomInfo($room_id);
            if($pwd == $room_info['password'])
            {
                return responseJson(200,'success');
            }else{
                return responseJson(400,'房间密码错误');
            }
        }else{
            $this->assign('room_id', $room_id);
            return $this->fetch('public/room_lock');
        }
    }

    /**
     * 获取历史消息
     */
    public function getMessage()
    {
        $user_info  = session('user_info');
        $room_info  = $this->getRoomInfo($user_info['room_id']);
        $power_role = explode(',', $room_info['power_role']);
        $is_examine = 1;
        if(in_array($user_info['user_role'], $power_role))
        {
            $is_examine = 0;
        }
        $room_id   = (int)input('room_id');
        $page      = (int)input('page',1);
        $limit     = 10;
        $room_msg  = 'room_msg_'.$room_id;
        $start   = 0-($page*$limit);
        $end     = 0-(($page - 1) *$limit);
        if($end === 0)
        {
            $end-= 1;
        }
        $list = $this->getRedisMessage($room_msg, $start, $end, $is_examine);
        return json($list);
    }

    public function saveUrl()
    {
        $url = input('url');
        $title = input('title','直播间');
        if(!$url)
        {
            die();
        }
        $Shortcut = "[InternetShortcut] 
        URL=".$url." 
        IDList= 
        [{000214A0-0000-0000-C000-000000000046}] 
        Prop3=19,2";
        Header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=".$title.".url;");
        echo $Shortcut;
    }

    /*
     * 上传图片
     */
    public function uploadImage()
    {
        $file = request()->file('file');
        if($file)
        {
            $date = date('Ymd');
            $root_path = '../public/static/uploads/images/' . $date;
            $root_path = str_replace('\\', '/', $root_path);
            //大小限制 3M
            $info = $file->rule('uniqid')->validate(['size' => 3145728, 'ext' => 'jpg,png,gif,jpeg'])->move($root_path);
            if($info){
                $file_name = $info->getSaveName();
                $file_path = $root_path . '/' . $info->getSaveName();
                $data['src'] = '/static/uploads/images/'.$date.'/'.$file_name;
                return responseJson(200, '上传成功', $data);
            }else{
                return responseJson(400,'上传失败');
            }

        }
    }


    public function test()
    {

    }

}
